package com.vitas.coin.ui.adapter

import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.snap.base.ktx.judgeCanUse
import com.snap.base.util.BaseUtil
import com.snap.util.startAct
import com.vitas.coin.R
import com.vitas.coin.callback.MusicAdapterCallback
import com.vitas.coin.constant.AppConstant
import com.vitas.coin.data.bean.ChildrenVoiceBean
import com.vitas.coin.data.event.CollectEvent
import com.vitas.coin.manager.LocalMusicManager
import com.vitas.coin.ui.act.BuyAct
import com.vitas.coin.ui.act.PlayAct
import com.vitas.coin.util.AdUtil
import com.vitas.coin.util.DisplayUtil
import com.vitas.coin.util.RenderViewOutlineProvider
import com.vitas.coin.view.RoundImageView

class MusicAdapter(
    context: FragmentActivity,
    dataList: ArrayList<ChildrenVoiceBean>
) : RecyclerView.Adapter<MusicAdapter.ViewHolder>() {

    var context: FragmentActivity? = null
    var dataList: ArrayList<ChildrenVoiceBean> = arrayListOf()
    lateinit var mMusicAdapterCallback: MusicAdapterCallback
    private var type = 0

    init {
        this.context = context
        this.dataList = dataList
    }

    fun setDownloadCallBack(mCallBack: MusicAdapterCallback) {
        this.mMusicAdapterCallback = mCallBack;
    }

    /**
     * 1 首页 2故事页
     */
    fun setType(type: Int) {
        this.type = type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_music, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val mItemData: ChildrenVoiceBean = dataList[position];
        holder.tv_name.text = mItemData.name
        holder.tv_duration.text =
            LocalMusicManager.getInstance(holder.tv_duration.context).duration(mItemData.timeLength)
        Glide.with(holder.iv_share.context).load(mItemData.avatarUrl)
            .apply(baseOptions(R.mipmap.img_avatar)).into(holder.iv_share)
        Glide.with(holder.iv_cover.context).load(mItemData.coverUrl)
            .apply(baseOptions(R.mipmap.img_default)).into(holder.iv_cover)
        holder.iv_cover.outlineProvider =
            RenderViewOutlineProvider(DisplayUtil.dip2px(holder.iv_cover.context, 9f))
        holder.iv_cover.clipToOutline = true
        if (mItemData.isCollect) {
            holder.iv_star.setImageResource(R.mipmap.icon_star_collected)
        } else {
            holder.iv_star.setImageResource(R.mipmap.icon_star_normal)
        }

        if (type == 2 && position == dataList.size - 1) {
            holder.bottom_line.visibility = View.INVISIBLE
        } else {
            holder.bottom_line.visibility = View.VISIBLE
        }

        holder.iv_lingsheng.setOnClickListener { v ->
            this.context?.let {
                BaseUtil.judgeCanUse(it, reduce = false, can = {
                    mMusicAdapterCallback.clickDownload(mItemData, 2)
                }, buy = {
                    startAct(BuyAct::class.java)
                })
            }
        }

        holder.cut.setOnClickListener { v ->
            this.context?.let {
                BaseUtil.judgeCanUse(it, reduce = false, can = {
                    mMusicAdapterCallback.clickDownload(mItemData, 1)
                }, buy = {
                    startAct(BuyAct::class.java)
                })
            }
        }

        holder.iv_star.setOnClickListener { v ->
            mMusicAdapterCallback.clickCollect(mItemData)
            BaseUtil.postEvent(CollectEvent(mItemData))
        }


        holder.itemView.setOnClickListener { v ->
            if (!TextUtils.isEmpty(mItemData.name) && !TextUtils.isEmpty(mItemData.voiceUrl)) {
                var i = Intent(holder.itemView.context, PlayAct::class.java)
                i.putExtra("index", holder.adapterPosition)
                i.putParcelableArrayListExtra("list", getList())
                holder.itemView.context.startActivity(i)
            }
        }

        if (position % 2 == 0) {
            context?.let {
                AdUtil.adNative(it, holder.ad_native)
            }
        }
    }

    fun getList(): ArrayList<ChildrenVoiceBean> {
        return dataList
    }

    private fun baseOptions(@DrawableRes placeholderImg: Int): RequestOptions {
        return RequestOptions().centerCrop()
            .placeholder(placeholderImg)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        super.onBindViewHolder(holder, position, payloads)
        for (obj in payloads) {
            if (obj !is String) {
                super.onBindViewHolder(holder, position, payloads)
                return
            }
        }

        for (payLoadsCache in payloads) {
            val key = payLoadsCache as String?
            when (key) {
                AppConstant.UPDATE_COLLECT_STATUS -> updateCollectStatus(holder, position)
                else -> {}
            }
        }
    }


    private fun updateCollectStatus(holder: ViewHolder, position: Int) {
        val mItemData: ChildrenVoiceBean = dataList[position]
        if (mItemData.isCollect) {
            holder.iv_star.setImageResource(R.mipmap.icon_star_collected)
        } else {
            holder.iv_star.setImageResource(R.mipmap.icon_star_normal)
        }
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tv_name: TextView = itemView.findViewById(R.id.tv_name)
        val tv_duration: TextView = itemView.findViewById(R.id.tv_duration)
        val iv_share: RoundImageView = itemView.findViewById(R.id.iv_share)
        val iv_lingsheng: AppCompatImageView = itemView.findViewById(R.id.iv_lingsheng)
        val iv_download: AppCompatImageView = itemView.findViewById(R.id.iv_download)
        val iv_star: AppCompatImageView = itemView.findViewById(R.id.iv_star)
        val bottom_line: View = itemView.findViewById(R.id.bottom_line)
        val iv_cover: AppCompatImageView = itemView.findViewById(R.id.iv_cover)
        val cut = itemView.findViewById<View>(R.id.cut)
        val ad_native: FrameLayout = itemView.findViewById(R.id.ad_native)
    }

}